import './App.css';
import { io } from 'socket.io-client';
import { useEffect, useRef, useState } from 'react';
import TextField from '@mui/material/TextField';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Button, Typography } from '@mui/material';
import AssignmentIcon from '@mui/icons-material/Assignment';
import PhoneIcon from '@mui/icons-material/Phone';
import CallEndIcon from '@mui/icons-material/CallEnd';
import SignalCellularAltIcon from '@mui/icons-material/SignalCellularAlt';
import SignalCellularConnectedNoInternet0BarIcon from '@mui/icons-material/SignalCellularConnectedNoInternet0Bar';
import RefreshIcon from '@mui/icons-material/Refresh';
import CircularProgress from '@mui/material/CircularProgress';

import Peer from 'simple-peer';

//客户端的socket连接
const socket = io('http://localhost:12345');

function App() {

  // socket连接状态
  const [socketConnected, setSocketConnected] = useState(true);

  // 视频连接状态
  const [connectionStatus, setConnectionStatus] = useState('disconnected'); // 'disconnected', 'connecting', 'connected', 'unstable'

  // 调用者信令
  const [offerSignal, setOfferSignal] = useState('');


  // connectionRef
  const connectionRef = useRef(null);

  // 创建存储状态
  const [stream, setStream] = useState(null);

  // 创建姓名状态
  const [myName, setMyName] = useState('默认名称');

  // 我的ID
  const [myId, setMyId] = useState('');

  // 创建视频元素
  const myVideoRef = useRef(null);

  // 接收者姓名
  const [toName, setToName] = useState('');

  // 待呼叫的id
  const [toId, setToId] = useState('');

  // 创建对端连接对象
  const toVideoRef = useRef(null);

  // 接收状态
  const [callAccepted, setCallAccepted] = useState(false);

  // 结束通话
  const [callEnded, setCallEnded] = useState(false);

  // 接听电话中
  const [receivingCall, setReceivingCall] = useState(false);


  // 调用者姓名
  const [caller, setCaller] = useState('');


  // 重新连接socket获取新ID
  const reconnectSocket = () => {
    console.log('尝试重新连接socket...');
    setSocketConnected(false);

    // 断开当前连接
    if (socket) {
      socket.disconnect();
    }

    // 重新连接
    setTimeout(() => {
      socket.connect();
      setSocketConnected(true);
      console.log('socket重新连接完成');
    }, 1000);
  };

  // 通过信令服务器,建立/断开连接
  useEffect(() => {
    setTimeout(() => {
      navigator.mediaDevices.getUserMedia({ 'audio': false, 'video': true })
        .then(stream => {
          setStream(stream)
          console.log('尝试显示本地stream')
          if (myVideoRef.current) {
            myVideoRef.current.srcObject = stream
          }
        })
        .catch(err => {
          console.log('获取视频流失败: ' + err)
        })
    }, 500);



    //接收端
    socket.on('connect_success', (id) => {
      console.log('连接成功,返回连接ID:', id);
      setMyId(id);
      setSocketConnected(true);
    })

    // 收到电话
    socket.on('receiveCall', ({ signal, from, name, userToCall }) => {
      console.log(`收到来自 ${name} (${from}) 的呼叫，信号:`, signal);
      setReceivingCall(true);
      setCaller(from);
      setToName(name);
      setToId(from)
      setOfferSignal(signal);
    })


    // 对方接收了通话
    socket.on('callAccepted', ({ signal, name }) => {
      console.log(`${name} 接受了通话，收到信号:`, signal);
      setCallAccepted(true);
      setToName(name);

      // 直接将信号应用到当前连接
      if (connectionRef.current) {
        try {
          console.log('呼叫方准备接收接听方的answer信号');
          connectionRef.current.signal(signal);
          console.log('呼叫方成功接收接听方的answer信号');
        } catch (error) {
          console.error('应用信号时出错:', error);
        }
      } else {
        console.error('连接对象不存在，无法应用信号');
      }
    })

    // 结束通话
    socket.on('callEnded', () => {
      console.log('通话已结束');
      setCallEnded(true);
      setConnectionStatus('disconnected');
      if (connectionRef.current) {
        try {
          connectionRef.current.destroy();
        } catch (error) {
          console.error('结束通话时出错:', error);
        }
      }
    })

    // 连接错误
    socket.on('callError', ({ message }) => {
      console.error('连接错误:', message);
      setConnectionStatus('disconnected');
    })

    // 组件卸载时清理
    return () => {
      socket.off('connect_success');
      socket.off('callUser');
      socket.off('callAccepted');
      socket.off('callEnded');
      socket.off('callError');

    };
  }, [])

  // 拨打电话
  const callUser = (id) => {
    if (!id.trim()) {
      alert('请输入有效的通话ID');
      return;
    }

    if (!myName.trim()) {
      alert('请输入您的姓名');
      return;
    }

    // 重置之前的连接状态
    setCallAccepted(false);
    setCallEnded(false);

    // 更新连接状态为连接中
    setConnectionStatus('connecting');
    console.log(`正在呼叫 ${id}`);

    // 确保有本地流
    if (!stream) {
      console.error('本地视频流不存在');
      alert('无法访问摄像头或麦克风，请检查设备权限');
      return;
    }

    try {
      // 销毁之前的连接
      if (connectionRef.current) {
        console.log('销毁之前的连接');
        try {
          connectionRef.current.destroy();
        } catch (error) {
          console.error('销毁之前连接时出错:', error);
        }
        connectionRef.current = null;
      }

      console.log('创建新的Peer连接(呼叫方)');
      const callerPeer = new Peer({
        initiator: true,
        stream: stream,
        trickle: false,
        config: {
          iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:global.stun.twilio.com:3478' },
            { urls: 'stun:stun1.l.google.com:19302' },
            { urls: 'stun:stun2.l.google.com:19302' },
            { urls: 'stun:stun3.l.google.com:19302' },
            { urls: 'stun:stun4.l.google.com:19302' }
          ]
        },
        sdpTransform: (sdp) => {
          console.log('呼叫方 | SDP:', sdp);
          return sdp;
        }
      });

      // 监听连接成功
      callerPeer.on('signal', (data) => {
        console.log('呼叫方生成信号:', data);
        // 传递信令数据
        try {
          socket.emit('sendCall', {
            userToCall: id,
            signal: data,  // 修改参数名从signalData为signal，与服务器端匹配
            from: myId,
            name: myName
          });
          console.log('呼叫信号已发送到服务器');
        } catch (error) {
          console.error('发送呼叫信号时出错:', error);
          alert(`发送呼叫信号失败: ${error.message}`);
        }
      });

      // 监听连接状态
      callerPeer.on('connect', () => {
        console.log('呼叫方P2P连接已建立');
        setConnectionStatus('connected');
      });

      callerPeer.on('stream', (remoteStream) => {
        console.log('呼叫方接收到对方视频流', remoteStream);

        // 保存远程流到状态变量，确保在DOM渲染后可以使用
        const savedRemoteStream = remoteStream;

        // 将视频流赋值给视频元素的函数
        const setVideoStream = () => {
          console.log('检查视频元素引用状态:', toVideoRef.current ? '存在' : '不存在');

          if (toVideoRef.current) {
            console.log('远程视频元素存在，设置视频流');
            try {
              // 确保视频元素可见
              toVideoRef.current.style.display = 'block';

              // 设置srcObject
              toVideoRef.current.srcObject = savedRemoteStream;
              console.log('已设置srcObject:', toVideoRef.current.srcObject);

              // 添加错误处理
              toVideoRef.current.onerror = (e) => {
                console.error('远程视频加载错误:', e);
                socket.emit('connectionError', { to: id, message: '远程视频加载错误' });
              };

              return true; // 成功设置
            } catch (err) {
              socket.emit('connectionError', { to: id, message: `远程视频加载错误未知异常: ${err.message}` });
              return false;
            }
          } else {
            socket.emit('connectionError', { to: id, message: '远程视频加载错误: 元素不存在' });
            return false;
          }
        };

        // 首次尝试设置视频流前先等待DOM渲染
        setVideoStream()
        // 更新连接状态为已连接
        setConnectionStatus('connected');
      });

      // 监听连接错误
      callerPeer.on('error', (err) => {
        console.error('呼叫方连接错误:', err);
        setConnectionStatus('unstable');
        // 检查是否是信号数据错误
        if (err.message.includes('signal')) {
          console.log('尝试重新初始化连接...');
          // 销毁当前连接并重新创建
          callerPeer.destroy();
          callUser(id);
        } else {
          socket.emit('connectionError', { to: id, message: `CallerPeer连接错误事件: ${err.message}` });
        }
      });

      // 监听连接关闭
      callerPeer.on('close', () => {
        console.log('呼叫方收到连接关闭事件');
        setConnectionStatus('disconnected');
        setCallEnded(true)
      });

      // 监听连接状态变化
      callerPeer.on('connectionStateChange', (state) => {
        console.log('呼叫方连接状态变化:', state);
        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          console.warn(`连接状态变为: ${state}`);
          setConnectionStatus('disconnected');
        } else if (state === 'connected') {
          console.log('连接成功建立');
          setConnectionStatus('connected');
        } else if (state === 'connecting') {
          console.log('正在建立连接...');
          setConnectionStatus('connecting');
        }
      });

      // 监听ICE连接状态变化
      callerPeer.on('iceConnectionStateChange', (state) => {
        console.log('呼叫方ICE连接状态变化:', state);
        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          console.warn(`ICE连接状态变为: ${state}`);
          setConnectionStatus('disconnected');
          // 尝试重新协商连接
          if (state === 'disconnected') {
            console.log('尝试恢复ICE连接...');
            try {
              // 重新启动ICE收集
              callerPeer.restartIce();
            } catch (error) {
              console.error('恢复ICE连接失败:', error);
            }
          }
        } else if (state === 'connected' || state === 'completed') {
          console.log(`ICE连接成功建立,状态: ${state}`);
          setConnectionStatus('connected');
        } else if (state === 'checking') {
          console.log('ICE正在检查连接候选项...');
          setConnectionStatus('connecting');
        }
      });

      // 不在这里使用接收方信号
      // 接收方信号会在callAccepted事件中处理

      callerPeer.on('data', data => {
        console.log('callerPeer | data: ' + data)
      })

      connectionRef.current = callerPeer;
    } catch (error) {
      console.error('创建Peer连接失败:', error);
      alert(`创建连接失败: ${error.message}`);
      socket.emit('connectionError', { to: id, message: `CallerPeer连接未知异常: ${error.message}` });
      setConnectionStatus('disconnected');
    }
  };

  // 结束通话
  const leaveCall = () => {
    setCallEnded(true);
    setConnectionStatus('disconnected');

    // 销毁连接
    if (connectionRef.current) {
      try {
        connectionRef.current.destroy();
      } catch (error) {
        console.error('结束通话时销毁连接出错:', error);
      }
    }

    // 通知服务器通话结束
    try {
      if (caller) {
        console.log(`通知呼叫方(${caller})通话结束`);
        socket.emit('callEnded', { to: caller });
      }
      if (toId) {
        console.log(`通知被呼叫方(${toId})通话结束`);
        socket.emit('callEnded', { to: toId });
      }
    } catch (error) {
      console.error('发送通话结束通知出错:', error);
    }

    console.log('通话已完全结束');
  }

  //接听电话
  const answerCall = () => {
    // 重置之前的连接状态
    setCallEnded(false);
    setCallAccepted(true);
    // 更新连接状态为连接中
    setConnectionStatus('connecting');
    console.log('已设置callAccepted为true，connectionStatus为connecting');
    console.log('接听电话 - 开始建立连接');

    // 确保有本地流
    if (!stream) {
      console.error('本地视频流不存在');
      alert('无法访问摄像头或麦克风，请检查设备权限');
      socket.emit('connectionError', { to: caller, message: '本地视频流不存在' });
      return;
    }

    // 确保有呼叫方信号
    if (!offerSignal) {
      console.error('没有呼叫方信号，无法建立连接');
      alert('连接信息不完整，请重新接听');
      socket.emit('connectionError', { to: caller, message: '呼叫方信号不存在' });
      return;
    }

    try {
      // 销毁之前的连接
      if (connectionRef.current) {
        console.log('销毁之前的连接');
        try {
          connectionRef.current.destroy();
        } catch (error) {
          console.error('销毁之前连接时出错:', error);
        }
        connectionRef.current = null;
      }

      console.log('接听电话: 创建新的接听方Peer连接');
      const receiverPeer = new Peer({
        //代表是发送answer信号
        initiator: false,
        stream: stream,
        trickle: false,
        config: {
          iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:global.stun.twilio.com:3478' },
            { urls: 'stun:stun1.l.google.com:19302' },
            { urls: 'stun:stun2.l.google.com:19302' },
            { urls: 'stun:stun3.l.google.com:19302' },
            { urls: 'stun:stun4.l.google.com:19302' }
          ]
        },
        sdpTransform: (sdp) => {
          console.log('接收方 | SDP:', sdp);
          return sdp;
        }
      })

      //如果收到signal事件,那么发送answer信号
      receiverPeer.on('signal', (data) => {
        console.log('接听方生成信号:', data);
        // 传递信令数据
        try {
          //发送answer信号
          socket.emit('answerCall', {
            signal: data,
            to: caller,
            name: myName // 添加名称信息
          });
          console.log('接听信号已发送到服务器');
        } catch (error) {
          console.error('发送接听信号时出错:', error);
          alert(`发送接听信号失败: ${error.message}`);
        }
      });

      // 监听连接状态
      receiverPeer.on('connect', () => {
        console.log('接听方P2P连接已建立');
        setConnectionStatus('connected');
      });


      try {
        // 应用呼叫方信号
        console.log('接听方准备接收呼叫方的offer信号:', offerSignal);
        receiverPeer.signal(offerSignal);
        console.log('接听方成功接收呼叫方的offer信号');
      } catch (error) {
        console.error('应用呼叫方信号时出错:', error);
        return;
      }

      // 监听ICE连接状态变化
      receiverPeer.on('iceStateChange', (state) => {
        console.log('接收方ICE连接状态变化:', state);
        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          console.warn(`ICE连接状态变为: ${state}`);
          setConnectionStatus('disconnected');
          // 尝试重新协商连接
          if (state === 'disconnected') {
            console.log('尝试恢复ICE连接...');
            try {
              // 可以在这里添加重新协商的逻辑
              // 例如重新发送信号或重新启动ICE收集
            } catch (error) {
              console.error('恢复ICE连接失败:', error);
            }
          }
        } else if (state === 'connected' || state === 'completed') {
          console.log(`ICE连接成功建立,状态: ${state}`);
          setConnectionStatus('connected');
        } else if (state === 'checking') {
          console.log('ICE正在检查连接候选项...');
          setConnectionStatus('connecting');
        }
      });

      receiverPeer.on('stream', (remoteStream) => {
        console.log('接听方接收到对方视频流', remoteStream);

        // 保存远程流到状态变量，确保在DOM渲染后可以使用
        const savedRemoteStream = remoteStream;


        // 将视频流赋值给视频元素的函数
        function setVideoStream() {
          if (toVideoRef.current) {
            try {
              console.log('远程视频元素存在，设置视频流');
              // 确保视频元素可见
              toVideoRef.current.style.display = 'block';

              // 设置srcObject
              toVideoRef.current.srcObject = savedRemoteStream;
              console.log('已设置srcObject:', toVideoRef.current.srcObject);

              // 添加错误处理
              toVideoRef.current.onerror = (e) => {
                console.error('远程视频加载错误:', e);
                socket.emit('connectionError', { to: caller, message: '呼叫方远程视频元素错误事件' });
              };

              // 添加状态变化监听
              // toVideoRef.current.onstalled = () => console.log('视频已暂停');
              // toVideoRef.current.onwaiting = () => console.log('视频等待中');
              // toVideoRef.current.onplaying = () => console.log('视频正在播放');

              console.log('成功设置:', toVideoRef.current.srcObject);
              return true; // 成功设置
            } catch (err) {
              socket.emit('connectionError', { to: caller, message: `呼叫方设置视频流错误: ${err.message}` });
              return false;
            }
          } else {
            console.log('远程视频元素不存在');
            socket.emit('connectionError', { to: caller, message: '视频流错误' });
            return false;
          }
        }

        // 确保视频元素存在后设置流
        if (setVideoStream()) {
          // 更新连接状态为已连接
          console.log('更新接收方状态为: 已连接')
          setConnectionStatus('connected');
        }
      })

      // 监听连接错误
      receiverPeer.on('error', (err) => {
        console.error('接听方连接错误:', err);
        setConnectionStatus('unstable');
        // 不要立即断开连接，尝试恢复
        console.log('尝试恢复连接...');
      })

      // 监听连接关闭
      receiverPeer.on('close', () => {
        console.log('接听方收到连接关闭事件');
        setConnectionStatus('disconnected');
        setCallEnded(true)
      })

      // 监听连接状态变化
      receiverPeer.on('connectionStateChange', (state) => {
        console.log('接听方连接状态变化:', state);
        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          console.warn(`连接状态变为: ${state}`);
          setConnectionStatus('disconnected');
        } else if (state === 'connected') {
          console.log('连接成功建立');
          setConnectionStatus('connected');
        } else if (state === 'connecting') {
          console.log('正在建立连接...');
          setConnectionStatus('connecting');
        }
      })

      // 监听ICE连接状态变化
      receiverPeer.on('iceConnectionStateChange', (state) => {
        console.log('接听方ICE连接状态变化:', state);
        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
          console.warn(`ICE连接状态变为: ${state}`);
          setConnectionStatus('disconnected');
          // 尝试重新协商连接
          if (state === 'disconnected') {
            console.log('尝试恢复ICE连接...');
            try {
              // 重新启动ICE收集
              receiverPeer.restartIce();
            } catch (error) {
              console.error('恢复ICE连接失败:', error);
            }
          }
        } else if (state === 'connected' || state === 'completed') {
          console.log(`ICE连接成功建立,状态: ${state}`);
          setConnectionStatus('connected');
        } else if (state === 'checking') {
          console.log('ICE正在检查连接候选项...');
          setConnectionStatus('connecting');
        }
      })

      receiverPeer.on('data', data => {
        console.log('receiverPeer | data: ' + data)
      })

      connectionRef.current = receiverPeer;
    } catch (error) {
      console.error('创建Peer连接失败:', error);
      socket.emit('connectionError', { to: caller, message: `创建连接失败: ${error.message}` });
      setConnectionStatus('disconnected');
    }
  }


  return (
    <div className="app-container">
      <h1 style={{ textAlign: 'center', color: '#3f51b5', marginBottom: '2rem' }}>视频聊天应用</h1>
      <div className='container'>
        <div className='video-container'>
          {/* 视频区域 */}
          <div className="videos-wrapper">
            {/* 本地视频 */}
            <div className="video-box">
              <h3 style={{ marginBottom: '0.5rem', color: '#555' }}>我的视频</h3>
              {stream && (
                <div className="video-frame">
                  <video
                    autoPlay
                    playsInline
                    muted
                    style={{
                      width: '100%',
                      maxWidth: '400px',
                      borderRadius: '8px',
                      boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
                    }}
                    ref={myVideoRef}
                    onLoadedMetadata={() => {
                      console.log('本地视频元数据已加载');
                    }}
                    onError={(e) => {
                      console.error('本地视频加载错误:', e);
                    }}
                  ></video>
                </div>
              )}
            </div>

            {/* 对方视频 */}
            <div className="video-box">
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
                <h3 style={{ color: '#555', margin: 0 }}>
                  {callAccepted && !callEnded ? `${toName || '对方'}的视频` : connectionStatus === 'connecting' ? '正在连接...' : '等待连接...'}
                </h3>
                {/* 连接状态指示器 */}
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  {/* 当callAccepted为true且callEnded为false时，显示已连接状态 */}
                  {callAccepted && !callEnded && connectionStatus !== 'disconnected' && (
                    <div style={{ display: 'flex', alignItems: 'center', color: '#2e7d32' }}>
                      <SignalCellularAltIcon style={{ marginRight: '4px' }} />
                      <span>通话中</span>
                    </div>
                  )}
                  {connectionStatus === 'connecting' && (
                    <div style={{ display: 'flex', alignItems: 'center', color: '#ed6c02' }}>
                      <CircularProgress size={16} color="warning" style={{ marginRight: '4px' }} />
                      <span>连接中...</span>
                    </div>
                  )}
                  {connectionStatus === 'unstable' && callAccepted && !callEnded && (
                    <div style={{ display: 'flex', alignItems: 'center', color: '#d32f2f' }}>
                      <SignalCellularConnectedNoInternet0BarIcon style={{ marginRight: '4px' }} />
                      <span>连接不稳定</span>
                    </div>
                  )}
                  {(connectionStatus === 'disconnected' || callEnded) && (
                    <div style={{ display: 'flex', alignItems: 'center', color: '#d32f2f' }}>
                      <SignalCellularConnectedNoInternet0BarIcon style={{ marginRight: '4px' }} />
                      <span>已断开</span>
                    </div>
                  )}
                </div>
              </div>
              <div className="video-frame">
                {/* 远程视频元素只在通话接通且未结束时显示 */}
                {callAccepted && !callEnded ? (
                  <video
                    autoPlay={true}
                    playsInline={true}
                    controls={true}
                    muted={true}
                    style={{
                      width: '100%',
                      maxWidth: '400px',
                      borderRadius: '8px',
                      boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
                    }}
                    ref={toVideoRef}
                    onLoadedMetadata={(e) => {
                      console.log('远程视频元数据已加载', e.target);
                      // 尝试立即播放视频
                      e.target.play().catch(err => {
                        console.error('自动播放失败:', err);
                      });
                    }}
                    onError={(e) => {
                      console.error('远程视频加载错误:', e);
                    }}
                  ></video>
                ) : (
                  <div style={{
                    width: '100%',
                    maxWidth: '400px',
                    height: '300px',
                    backgroundColor: '#f5f5f5',
                    borderRadius: '8px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#999'
                  }}>
                    <p>暂无视频</p>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 控制面板 */}
          <div className='control-panel'>
            <div className='user-info'>
              <TextField
                fullWidth
                id="filled-basic"
                label="姓名"
                variant="outlined"
                style={{ marginBottom: '20px' }}
                value={myName}
                onChange={(e) => {
                  const newName = e.target.value;
                  setMyName(newName);
                }}
              />

              <div style={{ display: 'flex', marginBottom: '20px' }}>
                <TextField
                  fullWidth
                  id="filled-basic"
                  label="我的通话ID"
                  variant="outlined"
                  value={myId}
                  InputProps={{ readOnly: true }}
                  style={{ marginRight: '10px' }}
                />
                <CopyToClipboard text={myId} onCopy={() => setMyId(socket.id)}>
                  <Button variant="contained" color='primary' style={{ minWidth: '50px', marginRight: '10px' }}>
                    <AssignmentIcon />
                  </Button>
                </CopyToClipboard>
                <Button
                  variant="contained"
                  color='secondary'
                  style={{ minWidth: '50px' }}
                  onClick={reconnectSocket}
                  disabled={!socketConnected}
                >
                  <RefreshIcon />
                </Button>
              </div>
              {!myId && (
                <Typography variant="body2" color="error" style={{ marginBottom: '10px' }}>
                  通话ID为空，请点击刷新按钮重新获取
                </Typography>
              )}

              <div style={{ display: 'flex', flexDirection: 'column', marginBottom: '20px' }}>
                <TextField
                  fullWidth
                  id="filled-basic"
                  label="请输入对方通话ID"
                  variant="outlined"
                  value={toId}
                  onChange={(e) => setToId(e.target.value)}
                />
              </div>

              <div className='call-controls'>
                {callAccepted && !callEnded ? (
                  <Button
                    variant='contained'
                    color='error'
                    fullWidth
                    size="large"
                    startIcon={<CallEndIcon />}
                    onClick={() => leaveCall()}
                  >
                    结束通话
                  </Button>
                ) : (
                  <Button
                    variant='contained'
                    color='primary'
                    fullWidth
                    size="large"
                    startIcon={<PhoneIcon />}
                    onClick={() => callUser(toId)}
                    disabled={!toId.trim() || !myName.trim()}
                  >
                    拨打电话
                  </Button>
                )}
              </div>

              {/* 通话状态 */}
              {callAccepted && !callEnded && (
                <div style={{
                  marginTop: '20px',
                  padding: '10px',
                  backgroundColor: '#e8f5e9',
                  borderRadius: '4px',
                  textAlign: 'center'
                }}>
                  <span style={{ color: '#2e7d32', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <span style={{
                      width: '10px',
                      height: '10px',
                      backgroundColor: '#2e7d32',
                      borderRadius: '50%',
                      display: 'inline-block',
                      marginRight: '8px'
                    }}></span>
                    通话进行中
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* 同意接听 */}
          {receivingCall && !callAccepted && (
            <div className='incoming-call'>
              <div style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0,0,0,0.7)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000
              }}>
                <div style={{
                  backgroundColor: 'white',
                  padding: '30px',
                  borderRadius: '8px',
                  textAlign: 'center',
                  maxWidth: '400px'
                }}>
                  <h2 style={{ marginBottom: '20px' }}>{toName}正在呼叫...</h2>
                  <Button
                    variant='contained'
                    color='primary'
                    size="large"
                    onClick={answerCall}
                    style={{ marginRight: '10px' }}
                  >
                    接听
                  </Button>
                  <Button
                    variant='outlined'
                    color='error'
                    size="large"
                    onClick={() => setReceivingCall(false)}
                  >
                    拒绝
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default App;